package com.zlzlib.libdata.helper;

import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;

import com.zlzlib.libdata.util.MyDateTimeUtil;
import com.zlzlib.libdata.util.MyFileUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 捕获全局异常的工具类
 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.
 *
 * @author zlz
 */
public abstract class BaseCrashHelper implements UncaughtExceptionHandler {

    /**
     * 系统默认的UncaughtException处理类
     */
    private UncaughtExceptionHandler mDefaultHandler;

    protected Context context;
    /**
     * 用来存储设备信息和异常信息
     */
    private final Map<String, String> infos = new HashMap<>();
    /**
     * 用于格式化日期,作为日志文件名的一部分
     */
    private final DateFormat formatter = MyDateTimeUtil.getMyDateFormat("yyyy-MM-dd-HH-mm-ss");
    //如果为null 表示不存入本地
    private String savePath = null;

    //此处可执行提示错误
    protected abstract void tipException(String msg);

    protected abstract void endException();

    /**
     * 初始化
     *
     * @param savePath 存储崩溃日志的本地文件地址
     */
    public void init(Context context, String savePath) {
        this.context = context;
        this.savePath = savePath;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 获取系统默认的UncaughtException处理器
        Thread.setDefaultUncaughtExceptionHandler(this);// 设置该CrashHandler为程序的默认处理器
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {// 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        endException();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (mDefaultHandler == null) return false;
        if (ex == null) return false;
        collectDeviceInfo(context);// 收集设备参数信息
        final String exMsg = getThrowableInfo(ex);//生成错误信息
        saveCrashInfo2File(exMsg);// 保存日志文件
        ex.printStackTrace();
        new Thread() {
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    tipException(exMsg);
                    // 去掉提示栏信息，避免用户误点
                    NotificationManager nfm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    nfm.cancelAll();
                    Looper.loop();
                } catch (Exception e) {
                    // 交由系统处理该异常
                    e.printStackTrace();
                    mDefaultHandler.uncaughtException(Thread.currentThread(), e);
                }
            }
        }.start();
        return true;
    }

    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    private void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = String.valueOf(pi.versionCode);
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
            infos.put("SDK_INT", Build.VERSION.SDK_INT + "");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        //通过反射获得系统信息
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Desc: 获得错误信息
     * @DateTime: 2020/2/5 16:33
     * @Author zlz
     */
    private String getThrowableInfo(Throwable ex) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key).append("=").append(value).append("\n");
        }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        return sb.toString();
    }

    /**
     * 保存错误信息到文件中
     *
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    private String saveCrashInfo2File(String ex) {
        if (savePath == null) {
            return "";
        }
        long timestamp = System.currentTimeMillis();
        String time = formatter.format(new Date());
        String fileName = "crash-" + time + "-" + timestamp + ".log";
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                MyFileUtil.saveFile(savePath, fileName, ex.getBytes());
            }
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}